#include "userconfigs.h"
#include <QFile>
#include "log/cnslogger.h"
#include "cnsGlobal.h"
#include <QTextCodec>

UserConfigs::UserConfigs()
{
    m_iniFile = nullptr;
}

void UserConfigs::saveConfigFile()
{
    m_iniFile->sync();
}

void UserConfigs::settings_init()
{
    const QString path = property("filePath").toString();
    /*QString fileName;
    fileName = QCoreApplication::applicationDirPath();
    fileName += path;*/
    m_iniFile = new QSettings(path, QSettings::IniFormat);
    /*QFile file(path);
    if (false == file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        m_iniFile->beginGroup("section");
        m_iniFile->setValue("status", "false");
        m_iniFile->endGroup();
    }*/
}

void UserConfigs::setValue(const QString &section, const QString &key, const QString &value)
{
    m_iniFile->setIniCodec(QTextCodec::codecForName("System"));
    m_iniFile->beginGroup(section);
    m_iniFile->setValue(key, value);
    m_iniFile->endGroup();
}

void UserConfigs::removeNode(const QString &section)
{
    m_iniFile->setIniCodec(QTextCodec::codecForName("System"));
    m_iniFile->remove(section);
}

void UserConfigs::removeKey(const QString &section, const QString &key)
{
    m_iniFile->setIniCodec(QTextCodec::codecForName("System"));
    /*QString path = QString("%1/%2").arg(section).arg(key);
    m_iniFile->remove(path);*/
    m_iniFile->beginGroup(section);
    m_iniFile->remove(key);
    m_iniFile->endGroup();
}

QString UserConfigs::getValue(const QString &section, const QString &key)
{
    m_iniFile->setIniCodec(QTextCodec::codecForName("System"));
    QString path = QString("%1/%2").arg(section).arg(key);
    QString result = m_iniFile->value(path).toString();
    return result;
}

CNS_INIT(UserConfigs)
CNS_REGISTER_CNS_COM_FACTORY2(UserConfigs, CnsComponent)
CNS_INIT_END

